package br.com.ifba.sadd.admin.presentation.professor {
	import br.com.ifba.sadd.model.ModelLocator;
	import br.com.ifba.sadd.model.Professor;
	import br.com.ifba.sadd.model.ServiceLocator;

	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.events.CloseEvent;
	import mx.rpc.AsyncToken;
	import mx.rpc.Responder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	
	[Bindable]
	public class PesquisarProfessorPresentationModel
	{
		
		private var _model:ModelLocator = ModelLocator.getInstance();
		private var _professores:ArrayCollection = new ArrayCollection;
		private var _service:ServiceLocator = ServiceLocator.getInstance();
		
		public function PesquisarProfessorPresentationModel()
		{
		}
		
		/* ----------------- Geters e Seters ------------------*/
		
		public function get model():ModelLocator
		{
			return _model;
		}
			
		[ArrayElementType("br.com.ifba.sadd.model.Professor")]
		public function get professores():ArrayCollection
		{
			return _professores;
		}
		
		public function set professores(value:ArrayCollection):void
		{
			_professores = value;
		}
		
		/* ----------------- Funções de Crud ------------------*/
		
		public function pesquisar(value:String):void
		{
			var token:AsyncToken = _service.professorService.pesquisarProfessor(value.toUpperCase());
			token.addResponder(new Responder(handlePesquisar, handleFault));
		}
		
		public function remover(value:Professor):void
		{
			if(value != null){
				model.professor = value;
				Alert.show("Deseja excluir este item", "Alerta", Alert.YES | Alert.NO, null, deletar, null, Alert.YES);
			}
			else{
				Alert.show("Selecione um item na tabela");
			}
		}
		
		/* ----------------- Funções de Apoio ------------------*/
				
		private function deletar(event:CloseEvent):void
		{
			if(event.detail == Alert.YES)
			{
				var token:AsyncToken = _service.professorService.deletarProfessor(model.professor.usuario.id, model.professor.id);
				token.addResponder(new Responder(handleDeletar, handleFault));
			}
		}
		
		/* --------------------- handles ------------------------*/
		
		private function handlePesquisar(list:ResultEvent):void
		{
			professores = new ArrayCollection(list.result as Array);		
		}
		
		private function handleFault(event:FaultEvent):void
		{
			Alert.show(event.fault.faultString, "Erro!");
		}
				
		private function handleDeletar(event:ResultEvent):void
		{
			for(var i:int; i< professores.length; i++)
			{
				if(professores.getItemAt(i).nome == model.professor.nome)
				{
					professores.removeItemAt(i);
					model.professor = null;
					Alert.show("Cadastro removido com sucesso");
					break;
				}
			}
		}
	}
}